package com.shengqin.service.impl;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shengqin.controller.dawei.FaceAiClient;
import com.shengqin.controller.dawei.dto.FeatureReq;
import com.shengqin.controller.dawei.dto.FeatureResp;
import com.shengqin.controller.dawei.dto.HeaderParams;
import com.shengqin.controller.dawei.dto.PicInfo;
import com.shengqin.controller.dawei.util.DaWeiHeaderUtil;
import com.shengqin.entity.FaceFeature;
import com.shengqin.mapper.FaceFeatureMapper;
import com.shengqin.utils.FaceDataWriter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
public class FaceFeatureService extends ServiceImpl<FaceFeatureMapper, FaceFeature> {

    @Resource
    private FaceAiClient faceAiClient;
    @Resource
    private FaceDataWriter faceDataWriter;

    public FaceFeature getByStudyCode(String studyCode) {
        QueryWrapper<FaceFeature> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FaceFeature::getStudyCode, studyCode);
        return getOne(wrapper);
    }

    public List<FaceFeature> listByStudyCodes(Set<String> studyCodes) {
        QueryWrapper<FaceFeature> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(FaceFeature::getStudyCode, studyCodes);
        return list(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public FaceFeature getFaceFaceture(String studyCode, String imgBase64, File file) {
        try {
            FeatureReq featureReq = new FeatureReq();
            HeaderParams req = DaWeiHeaderUtil.getHeaderParams();
            featureReq.setTimestamp(req.getTimestamp());
            featureReq.setSign(req.getSign());
            PicInfo picInfo = new PicInfo();
            if (!StringUtils.hasLength(imgBase64) && file != null) {
                String base64Str = Base64.encode(file);
                picInfo.setBase64(base64Str);
            } else {
                picInfo.setBase64(imgBase64);
            }
            featureReq.setPic_info(picInfo);
            FeatureResp featureResp = faceAiClient.getFeature(featureReq);

            FaceFeature faceFeature = getByStudyCode(studyCode);
            if(faceFeature == null){
                faceFeature = new FaceFeature();
                faceFeature.setStudyCode(studyCode);
                faceFeature.setCreateTime(LocalDateTime.now());
            } else {
                faceFeature.setUpdateTime(LocalDateTime.now());
            }
            if(featureResp.getPic_feature() != null && featureResp.getPic_feature().length > 0){
                String faceData = Arrays.toString(featureResp.getPic_feature());
                faceData = faceData.replaceAll("\\[","");
                faceData = faceData.replaceAll("]","");
                faceFeature.setFaceData(faceData);
            }
            faceFeature.setFeatureVersion(featureResp.getFeature_version());
            faceFeature.setPicFeatureLen(featureResp.getPic_feature_len());
            String featureUrl = faceDataWriter.writeFaceData(faceFeature.getFaceData(),
                    featureResp.getFeature_version(),
                    featureResp.getPic_feature_len());
            faceFeature.setFeatureUrl(featureUrl);
            saveOrUpdate(faceFeature);
            return faceFeature;
        } catch (Exception e) {
            log.error("获取大沩人脸识别数据报错", e);
            return null;
        }
    }

    public FeatureResp getFaceFaceture(String imgBase64) {
        try {
            FeatureReq featureReq = new FeatureReq();
            HeaderParams req = DaWeiHeaderUtil.getHeaderParams();
            featureReq.setTimestamp(req.getTimestamp());
            featureReq.setSign(req.getSign());
            PicInfo picInfo = new PicInfo();
            picInfo.setBase64(imgBase64);
            featureReq.setPic_info(picInfo);
            return faceAiClient.getFeature(featureReq);
        } catch (Exception e) {
            log.error("获取大沩人脸识别数据报错", e);
            return null;
        }
    }
}
